package com.qunar.flight.myserver;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.log4j.Logger;

public class RequestHandler implements Handler {
	static Logger logger = Logger.getLogger(RequestHandler.class);
	ReentrantLock lock = new ReentrantLock();
	public  SocketChannel sc;
	private SelectionKey sk;
	private long infact=0;
	String status = null;
	long timestamp=0;

	RequestHandler(SocketChannel sc) {
		this.sc = sc;
	}

	public void setSk(SelectionKey sk) {
		this.sk = sk;
	}

	public void handle(SelectionKey sk) {
		FileChannel fc = null;
		long length = -1;
		ByteBuffer requestBB = ByteBuffer.allocate(1024 * 4);
		try {
			if (sc.isConnected()) {
				sc.read(requestBB);
			} else {
				logger.info("连接已关闭！！！");
				status="over";
				return;
			}
		} catch (Exception e1) {
			try {
				sc.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			e1.printStackTrace();
		}
		String rbb = new String(requestBB.array()).trim();
		logger.info("请求的内容" + rbb);
		if (rbb.indexOf("favicon.ico") > -1) {
			logger.info("包含非法请求内容favicon.ico");
			try {
				sc.close();
				status="error";
			} catch (Exception e) {
				e.printStackTrace();
			}
			return;
		}
		if (0 == rbb.length()) {
			logger.info("请求为空！");
			if (!"loop".equals(status)) {
				try {
					sc.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
				return;
			}
		}
		logger.info("处理中..." + sk.interestOps() + ":" + sk);
		if (-1 == length) {
			File fn = new File("d:\\shell.pdf");
			try {
				fc = new RandomAccessFile(fn, "r").getChannel();
				length = fc.size();
			} catch (Exception e) {
				e.printStackTrace();
			}
			logger.info("加载文件成功！length为：" + length);
		}
		try {
			long ms=fc.transferTo(infact, length - infact, sc);
			long laststamp=timestamp;
			timestamp=System.currentTimeMillis();
			infact += ms;
			System.out.println("下载进度："+infact*100/length+"  下载速度："+ms/(timestamp-laststamp)+"KB/s");
			logger.info("当前线程:"+Thread.currentThread());
		} catch (Exception e) {
			e.printStackTrace();
		}
		boolean flag = false;
		if (!flag || infact >= length) {
			if (infact < length) {
				flag = true;
				status = "loop";
				sk.interestOps(SelectionKey.OP_WRITE);
				logger.info("还没写完");
			} else {
				logger.info("擦除status");
				status = "over";
				try {
					sc.close();
					if (fc != null) {
						fc.close();
						fc = null;
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						sc.close();
						if (fc != null) {
							fc.close();
							fc = null;
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				logger.info("终于写完");
				try {
					sc.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	public void run() {
		lock.lock();
		try {
			handle(sk);
		} catch (Exception e) {
			logger.error(e);
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
}
